package com.trsj.lnsj.util.wechat;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.trsj.lnsj.common.DataResponse;
import com.trsj.lnsj.common.MsgStatus;
import com.trsj.lnsj.util.ResponseHelper;

public class WechatPayUtil {
    private static Logger logger = LoggerFactory.getLogger(WechatPayUtil.class);

    /**
     * 调用微信统一下单接口
     **/
    public static DataResponse weixinPay(BigDecimal totalAmount, String notifyUrl) {
        String appId = WechatPayConfig.WECHAT_APPID;//request.getParameter("appId");
        String openid = WechatPayConfig.WECHAT_APPSECRET;//request.getParameter("openid");
        String mchId = WechatPayConfig.WECHAT_MCHID;//request.getParameter("mchId");
        String apiKey = WechatPayConfig.WECHAT_APPKEY;//request.getParameter("apiKey");
        if (StringUtils.isBlank(appId) || StringUtils.isBlank(mchId)
                || StringUtils.isBlank(apiKey)) {
            logger.info("appId=" + appId + "; openid=" + openid + "; mchId=" + mchId + "; apiKey=" + apiKey);
            return ResponseHelper.getResponse(MsgStatus.STATUS_FAILED, "获取请求参数失败");
        }
        SortedMap<String, Object> parameterMap = new TreeMap<String, Object>();
        String outTradeNo = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
        parameterMap.put("appid", appId);
        parameterMap.put("attach", "支付测试");
        parameterMap.put("body", "快乐APP支付测试");
        parameterMap.put("mch_id", mchId);
        parameterMap.put("nonce_str", UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32));
        parameterMap.put("notify_url", notifyUrl);// "http://xxx.com"
        parameterMap.put("out_trade_no", outTradeNo);
        parameterMap.put("spbill_create_ip", "127.0.0.1");//request.getRemoteAddr()
//        BigDecimal total = totalAmount.multiply(new BigDecimal(100));
        java.text.DecimalFormat df = new java.text.DecimalFormat("0");
        parameterMap.put("total_fee", df.format(totalAmount).toString());
        parameterMap.put("trade_type", "APP");
        String sign = CommonUtil.createSign("UTF-8", parameterMap, apiKey);
        parameterMap.put("sign", sign);

        String requestXML = CommonUtil.getRequestXml(parameterMap);
        logger.info(requestXML);
        String result = CommonUtil.httpsRequest("https://api.mch.weixin.qq.com/pay/unifiedorder", "POST", requestXML);
        logger.info(result);
        Map<String, String> map = null;
        JSONObject jsonObject = new JSONObject();
        SortedMap<String, Object> signParam = new TreeMap<String, Object>();
        try {
            map = CommonUtil.doXMLParse(result);
            String return_code = map.get("return_code");
            String prepay_id = null;
            if (return_code.contains("SUCCESS")) {
                prepay_id = map.get("prepay_id");// 获取到prepay_id
            }
            long currentTimeMillis = System.currentTimeMillis();// 生成时间戳
            long second = currentTimeMillis / 1000L;// （转换成秒）
            String seconds = String.valueOf(second).substring(0, 10); // 截取前10位

            signParam.put("appId", appId);// app_id
            signParam.put("package", "prepay_id=" + prepay_id);// 默认sign=WXPay
            signParam.put("nonceStr", CommonUtil.getRandomString(32));// 自定义不重复的长度不长于32位
            signParam.put("timeStamp", seconds);// 北京时间时间戳
            signParam.put("signType", "MD5");// 北京时间时间戳
            String signAgain = CommonUtil.createSign("UTF-8", signParam, WechatPayConfig.WECHAT_APPKEY);// 再次生成签名
            signParam.put("paySign", signAgain);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseHelper.getSuccessResponse("paramterMap", signParam);
    }
    
    private static String getSign() {
        String appId = WechatPayConfig.WECHAT_APPID;//request.getParameter("appId");
        String mchId = WechatPayConfig.WECHAT_MCHID;//request.getParameter("mchId");
        String appsrt = WechatPayConfig.WECHAT_APPSECRET;//request.getParameter("apiKey");
        String nonceStr = "deed8994d5df419e8a50afb2830cb681";//UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
        String sign=MD5Util.MD5Encode("appid="+appId+"&body="+nonceStr+"&mch_id="+mchId+"&nonce_str="+nonceStr+"&key="+appsrt, "UTF-8").toUpperCase();
        String outTradeNo = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
        SortedMap<String, Object> parameters = new TreeMap<String, Object>();
        parameters.put("appid", appId);
        parameters.put("mch_id", mchId);
        parameters.put("body", "test");
        parameters.put("sign", sign);
        parameters.put("out_trade_no", outTradeNo);
        parameters.put("nonce_str", nonceStr);
        String signStr = CommonUtil.getRequestXml(parameters);
        return signStr;
    }

    public static void main(String[] args) {
        System.out.println(getSign());
//        System.out.println(weixinPay(new BigDecimal(100), "127.0.0.1"));
    }
}
